import { createRouter, createWebHistory, RouteRecordRaw, NavigationGuardNext, RouteLocationNormalized } from 'vue-router'
import { getToken } from '@/utils/auth'
import MainLayout from '@/layouts/MainLayout.vue'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: MainLayout,
    children: [
      {
        path: '',
        redirect: '/sub/dashboard',
      },
      {
        path: '/sub/:pathMatch(.*)*',
        name: 'SubApp',
        component: () => import('@/pages/SubAppContainer.vue'),
        meta: { requiresAuth: true }
      },
      {
        path: '/login',
        name: 'Login',
        component: () => import('@/pages/Login.vue'),
        meta: { requiresAuth: false }
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {

  console.log(`路由守卫${to.path}`)
  const hasToken = !!getToken()
  const isLoginPage = to.path === '/login'
  
  // 保存原始要访问的路由，登录后跳转使用
  if (!hasToken && !isLoginPage) {
    sessionStorage.setItem('redirect_url', to.fullPath)
  }
  if (!hasToken && !isLoginPage) {
    // 未登录且访问的不是登录页，重定向到登录页
    next('/login')
  } else if (hasToken && isLoginPage) {
    // 已登录还访问登录页，获取之前保存的跳转地址或默认跳转到首页
    const redirectUrl = sessionStorage.getItem('redirect_url') || '/dashboard'
    sessionStorage.removeItem('redirect_url')
    next(redirectUrl)
  } else {
    next()
  }
})

export default router 